<script setup lang="ts">
import TitleGroup from "@/components/FormRowTitle/index.vue";
import { ElMessageBox, ElNotification } from "element-plus";
import { RefreshLeft, Search, Plus, Grid } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import {
  getTradeMltContract,
  addTradeMltContract,
  editTradeMltContract,
  delTradeMltContract
} from "@/api/tradeMltContract";
import fileList from "@/views/business/vppUser/vppFile.vue";
import { useRouter } from "vue-router";
const router = useRouter();
const detail = row => {
  router.push({
    path: "/electricitySalesManagement/longTimeDetail",
    query: {
      id: row.id,
      name: row.contractName
    }
  });
};
const activeTwoName = ref("first");
const loading = ref(false);
const queryForm = reactive({
  data: {
    contractNumber: undefined,
    contractName: undefined
  }
});
const contractTypeDict = [
  {
    value: 1,
    label: "年度双边协商交易"
  },
  {
    value: 2,
    label: "月度双边协商交易"
  },
  {
    value: 3,
    label: "月内双边协商交易"
  },
  {
    value: 4,
    label: "年度集中竞价交易"
  },
  {
    value: 5,
    label: "月度集中竞价交易"
  },
  {
    value: 6,
    label: "月内集中竞价交易"
  },
  {
    value: 7,
    label: "月度挂牌交易"
  },
  {
    value: 8,
    label: " 月内挂牌交易"
  },
  {
    value: 9,
    label: "月度滚动撮合交易"
  }
];
const priceTypeDict = [
  {
    value: 1,
    label: "固定交易价格模式"
  },
  {
    value: 2,
    label: "联动交易价格模式"
  }
];
const supplyModeDict = [
  {
    value: 1,
    label: "直接供电"
  },
  {
    value: 2,
    label: "通过电网"
  }
];
const tableColums = [
  {
    id: 1,
    label: "合同编号",
    key: "contractNumber",
    prop: "contractNumber",
    width: "200px",
    align: "center"
  },
  {
    id: 2,
    label: "合同名称",
    key: "contractName",
    prop: "contractName",
    width: "200px",
    align: "center"
  },
  {
    id: 3,
    label: "甲方（售电公司/电力用户）",
    key: "electricityConsumer",
    prop: "electricityConsumer",
    width: "500px",
    align: "center"
  },
  {
    id: 4,
    label: "乙方（发电企业）",
    key: "electricitySupplier",
    prop: "electricitySupplier",
    width: "500px",
    align: "center"
  },
  {
    id: 5,
    label: "丙方（电网企业：默认为山东电力交易市场）",
    key: "electricityGrid",
    prop: "electricityGrid",
    width: "500px",
    align: "center"
  },
  {
    id: 6,
    label: "合同电量",
    key: "electricityCount",
    prop: "electricityCount",
    width: "200px",
    align: "center"
  },
  {
    id: 7,
    label: "签订日期",
    key: "dateOfSigning",
    prop: "dateOfSigning",
    width: "200px",
    align: "center"
  },
  {
    id: 8,
    label: "生效日期",
    key: "effectiveDate",
    prop: "effectiveDate",
    width: "200px",
    align: "center"
  },
  {
    id: 9,
    label: "生效年份",
    key: "effectiveYears",
    prop: "effectiveYears",
    width: "200px",
    align: "center"
  },
  {
    id: 10,
    label: "执行首日",
    key: "executionFirstDay",
    prop: "executionFirstDay",
    width: "200px",
    align: "center"
  },
  {
    id: 11,
    label: "终止日期",
    key: "expiryDate",
    prop: "expiryDate",
    width: "200px",
    align: "center"
  },
  {
    id: 12,
    label: "执行终日",
    key: "executionEndDay",
    prop: "executionEndDay",
    width: "200px",
    align: "center"
  },
  {
    id: 13,
    label: "供电模式", //     @ApiModelProperty(value = "供电模式 1:直接供电 2:通过电网")
    key: "supplyMode",
    prop: "supplyMode",
    width: "200px",
    align: "center"
  },
  {
    id: 14,
    label: "价格模式", // "价格模式（1：固定交易价格模式 2：联动交易价格模式）")
    key: "priceType",
    prop: "priceType",
    width: "200px",
    align: "center"
  },
  {
    id: 15,
    label: "交易类型", // （对应附件7的10种类型）"
    key: "contractType",
    prop: "contractType",
    width: "200px",
    align: "center"
  }
];
const dictFormat = (key, value, data) => {
  if (value) {
    let item = data.find(i => parseInt(i.value) === parseInt(value));
    if (item) {
      return item.label;
    } else {
      return "";
    }
  } else {
    return "";
  }
};
const dictList = reactive({
  data: {
    priceType: priceTypeDict,
    contractType: contractTypeDict,
    supplyMode: supplyModeDict
  }
});
const search = async () => {
  pageObj.data.currentPage = 1;
  let res = await getData();
  tableData.data = res.content;
  pageObj.data.total = res.totalElements;
};
const getData = () => {
  loading.value = true;
  return new Promise<any>(async (resolve, reject) => {
    let data = await getTradeMltContract({
      current: pageObj.data.currentPage,
      size: pageObj.data.pageSize,
      ...queryForm.data
    });
    loading.value = false;
    resolve(data);
  });
};

const dataDelRow = async row => {
  await delTradeMltContract([row.id]);
};
const resetQuery = () => {
  queryForm.data = {
    contractNumber: undefined,
    contractName: undefined
  };
};
const pageObj = reactive({
  data: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
});
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = async () => {
  let res = await getData();
  tableData.data = res.content;
  pageObj.data.total = res.totalElements;
};
const tableData = reactive({
  data: []
});
const status = ref("add");
const edit = row => {
  title.value = "编辑中长期合同";
  activeTwoName.value = "first";
  addDialog.value = true;
  status.value = "edit";
  form.data = JSON.parse(JSON.stringify(row));
};
const look = row => {
  title.value = "查看中长期合同";
  activeTwoName.value = "first";
  addDialog.value = true;
  status.value = "look";
  form.data = JSON.parse(JSON.stringify(row));
};
const form = reactive({
  data: {
    contractNumber: undefined,
    contractName: undefined,
    electricityConsumer: undefined,
    electricitySupplier: undefined,
    electricityGrid: "山东电力交易市场",
    electricityCount: undefined,
    dateOfSigning: undefined,
    effectiveDate: undefined,
    effectiveYears: undefined,
    executionFirstDay: undefined,
    expiryDate: undefined,
    executionEndDay: undefined,
    supplyMode: undefined,
    priceType: undefined,
    contractType: undefined
  },
  rules: {
    contractNumber: [
      { required: true, message: "请输入合同编号", trigger: "blur" }
    ],
    contractName: [
      { required: true, message: "请输入合同名称", trigger: "blur" }
    ],
    electricityConsumer: [
      { required: true, message: "请输入甲方名称", trigger: "blur" }
    ],
    electricitySupplier: [
      { required: true, message: "请输入乙方名称", trigger: "blur" }
    ],
    electricityGrid: [
      { required: true, message: "请输入丙方名称", trigger: "blur" }
    ],
    electricityCount: [
      { required: true, message: "请输入合同电量", trigger: "change" }
    ],
    dateOfSigning: [
      { required: true, message: "请选择签订日期", trigger: "change" }
    ],
    effectiveDate: [
      { required: true, message: "请选择生效日期", trigger: "change" }
    ],
    executionFirstDay: [
      { required: true, message: "请选择执行首日", trigger: "change" }
    ],
    effectiveYears: [
      { required: true, message: "请输入生效年份", trigger: "change" }
    ],
    expiryDate: [
      { required: true, message: "请选择终止日期", trigger: "change" }
    ],
    executionEndDay: [
      { required: true, message: "请选择执行终日", trigger: "change" }
    ],
    supplyMode: [
      { required: true, message: "请选择供电模式", trigger: "change" }
    ],
    priceType: [
      { required: true, message: "请选择价格模式", trigger: "change" }
    ],
    contractType: [
      { required: true, message: "请选择交易类型", trigger: "change" }
    ]
  }
});
const del = row => {
  ElMessageBox.confirm("是否确认删除该中长期合同?", "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await dataDelRow(row);
    search();
    ElNotification({
      title: "系统提示",
      message: "删除成功",
      type: "success"
    });
  });
};
const formRules = ref(null);
const addDialog = ref(false);
const title = ref("添加");

const add = () => {
  title.value = "创建中长期合同";
  activeTwoName.value = "first";
  addDialog.value = true;
  status.value = "add";
};
const cancel = () => {
  form.data = {
    contractNumber: undefined,
    contractName: undefined,
    electricityConsumer: undefined,
    electricitySupplier: undefined,
    electricityGrid: "山东电力交易市场",
    electricityCount: undefined,
    dateOfSigning: undefined,
    effectiveDate: undefined,
    effectiveYears: undefined,
    executionFirstDay: undefined,
    expiryDate: undefined,
    executionEndDay: undefined,
    supplyMode: undefined,
    priceType: undefined,
    contractType: undefined
  };
  setTimeout(() => {
    formRules.value && formRules.value.clearValidate();
    addDialog.value = false;
  }, 0);
};
const subLoading = ref(false);
const submit = () => {
  subLoading.value = true;
  formRules.value.validate(async valid => {
    if (valid) {
      if (status.value === "add") {
        await addTradeMltContract(form.data);
        ElNotification({
          title: "系统提示",
          message: "中长期合同创建成功",
          type: "success"
        });
      } else {
        await editTradeMltContract(form.data);
        ElNotification({
          title: "系统提示",
          message: "中长期合同修改成功",
          type: "success"
        });
      }
      search();
      cancel();
    }
    subLoading.value = false;
  });
};
const init = () => {
  search();
};
const beforeClose = async d => {
  await cancel();
  d();
};
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);
const defaultColums = reactive({
  data: []
});
const colums = reactive({
  data: []
});
onMounted(() => {
  defaultColums.data = tableColums;
  colums.data = tableColums;
  init();
  checkedCities.value = colums.data.map(item => item.prop);
});
const queryShow = ref(true);
const getList = () => {
  search();
};

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
</script>

<template>
  <div class="main h-[calc(100%-29px)]">
    <el-card v-loading="loading" class="w-full my-card-full">
      <el-row v-if="queryShow">
        <el-form :inline="true" :model="queryForm.data" label-width="0px">
          <el-form-item>
            <el-input
              v-model="queryForm.data.contractNumber"
              placeholder="请输入合同编号查询"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="queryForm.data.contractName"
              placeholder="请输入合同名称查询"
            />
          </el-form-item>
          <!--          <el-form-item>-->
          <!--            <el-date-picker-->
          <!--              v-model="queryForm.data.dateOfSigning"-->
          <!--              type="daterange"-->
          <!--              range-separator=":"-->
          <!--              start-placeholder="合同签订日期段"-->
          <!--              end-placeholder="结束日期"-->
          <!--              value-format="YYYY-MM-DD"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item class="ml-[10px]">
            <el-button type="primary" :icon="Search" @click="search"
              >查询</el-button
            >
            <el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="w-full flex justify-between mb-[10px]">
        <div class="buttons flex align-center">
          <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
          <!--          <el-button-->
          <!--            type="success"-->
          <!--            :icon="Edit"-->
          <!--            :disabled="!(multipleSelection.length === 1)"-->
          <!--            @click="editSelect"-->
          <!--          >修改</el-button-->
          <!--          >-->
          <!--          <el-button-->
          <!--            type="danger"-->
          <!--            :icon="Delete"-->
          <!--            :disabled="!multipleSelection.length"-->
          <!--            @click="delSelect"-->
          <!--          >删除</el-button-->
          <!--          >-->
          <!--            <el-button type="warning" :icon="Download" @click="exportData"-->
          <!--              >导出</el-button-->
          <!--            >-->
        </div>
        <div class="settings">
          <el-button-group class="ml-4">
            <el-button
              type="primary"
              :icon="Search"
              @click="queryShow = !queryShow"
            />
            <el-button type="primary" :icon="RefreshLeft" @click="getList" />
            <el-popover placement="bottom" :width="200" trigger="click">
              <template #reference>
                <el-button type="primary" :icon="Grid" />
              </template>
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <div class="group-box w-full max-h-[240px] overflow-y-auto">
                <el-checkbox-group
                  v-model="checkedCities"
                  class="columns-show-group"
                  @change="handleCheckedCitiesChange"
                >
                  <el-checkbox
                    v-for="item in defaultColums.data"
                    :key="item.prop"
                    :label="item.prop"
                    >{{ item.label }}</el-checkbox
                  >
                </el-checkbox-group>
              </div>
            </el-popover>
          </el-button-group>
        </div>
      </div>
      <div class="w-full">
        <el-table :data="tableData.data" width="100%">
          <el-table-column
            v-for="item in colums.data"
            :key="item.id"
            :label="item.label"
            :prop="item.key"
            :width="item.width"
            :align="item.align"
          >
            <template
              v-if="
                ['supplyMode', 'priceType', 'contractType'].indexOf(item.prop) >
                -1
              "
              #default="scope"
            >
              <span>{{
                dictFormat(
                  item.prop,
                  scope.row[item.prop],
                  dictList.data[item.prop]
                )
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="300px"
            :fixed="'right'"
            label="操作"
            align="center"
          >
            <template #default="scope">
              <el-button text type="primary" @click="look(scope.row)"
                >查看</el-button
              >
              <el-button text type="primary" @click="detail(scope.row)"
                >详情</el-button
              >
              <el-button text type="primary" @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-button text type="primary" @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page w-full mt-[10px]">
        <el-pagination
          v-model:current-page="pageObj.data.currentPage"
          v-model:page-size="pageObj.data.pageSize"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageObj.data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog
      v-model="addDialog"
      :before-close="beforeClose"
      :title="title"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="w-full">
        <el-tabs
          v-if="status !== 'add'"
          v-model="activeTwoName"
          class="demo-tabs"
        >
          <el-tab-pane label="合同信息" name="first" />
          <el-tab-pane label="附件" name="second" />
        </el-tabs>
        <el-form
          v-if="activeTwoName === 'first'"
          ref="formRules"
          class="display-block"
          :model="form.data"
          label-width="160px"
          :rules="form.rules"
          :disabled="status === 'look'"
        >
          <TitleGroup title="合同基础信息">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同编号" prop="contractNumber">
                  <el-input
                    v-model="form.data.contractNumber"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同名称" prop="contractName">
                  <el-input
                    v-model="form.data.contractName"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同电量" prop="electricityCount">
                  <el-input-number
                    v-model="form.data.electricityCount"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="签订日期" prop="dateOfSigning">
                  <el-date-picker
                    v-model="form.data.dateOfSigning"
                    type="date"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                    date-format="YYYY-MM-DD"
                    :size="'default'"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生效日期" prop="effectiveDate">
                  <el-date-picker
                    v-model="form.data.effectiveDate"
                    type="date"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                    date-format="YYYY-MM-DD"
                    :size="'default'"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="执行首日" prop="executionFirstDay">
                  <el-date-picker
                    v-model="form.data.executionFirstDay"
                    type="date"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                    date-format="YYYY-MM-DD"
                    :size="'default'"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="终止日期" prop="expiryDate">
                  <el-date-picker
                    v-model="form.data.expiryDate"
                    type="date"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                    date-format="YYYY-MM-DD"
                    :size="'default'"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="执行终日" prop="executionEndDay">
                  <el-date-picker
                    v-model="form.data.executionEndDay"
                    type="date"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                    date-format="YYYY-MM-DD"
                    :size="'default'"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生效年份" prop="effectiveYears">
                  <el-input
                    v-model="form.data.effectiveYears"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供电模式" prop="supplyMode">
                  <el-select
                    v-model="form.data.supplyMode"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dictList.data.supplyMode"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="价格模式" prop="priceType">
                  <el-select v-model="form.data.priceType" placeholder="请选择">
                    <el-option
                      v-for="item in dictList.data.priceType"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交易类型" prop="contractType">
                  <el-select
                    v-model="form.data.contractType"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in dictList.data.contractType"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </TitleGroup>
          <TitleGroup title="各方信息">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="甲方" prop="electricityConsumer">
                  <el-input
                    v-model="form.data.electricityConsumer"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="乙方" prop="electricitySupplier">
                  <el-input
                    v-model="form.data.electricitySupplier"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="丙方" prop="electricityGrid">
                  <el-input
                    v-model="form.data.electricityGrid"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </TitleGroup>
        </el-form>
        <div v-if="status !== 'add' && activeTwoName === 'second'">
          <fileList
            :active-vpp-user-id="form.data.id"
            :handle-status="status"
            :module-type="'trade_mlt_contract'"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="status === 'look'" @click="cancel">关闭</el-button>
          <el-button v-if="status !== 'look'" @click="cancel">取消</el-button>
          <el-button
            v-if="status !== 'look'"
            :loading="subLoading"
            type="primary"
            @click="submit"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.my-card-full {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    .demo-tabs {
      display: flex;
      flex: 1;
      flex-direction: column;
      overflow: hidden;

      .el-tabs__content {
        flex: 1;

        .el-tab-pane {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
